import axios from 'axios'
import { ElMessage } from 'element-plus'
import md5 from 'js-md5'
import { isEmptyObject, dataSort, dataSerialize } from '.'
import CnkiMessage from '@/components/common/CnkiMessage'

// 参数签名的密钥，前端需要对该密钥通过md5再次加密，后端同样md5(publicKey)
const publicKey = 'oO4yrbbI20IQ7sci'

const service = axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? '/api' : process.env.VUE_APP_BASE_API,
  timeout: 30 * 1000, // request timeout
  headers: {},
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // 追加签名信息
    const timestamp = Date.now()
    // 文件不加签
    let signature = md5(timestamp + md5(publicKey))

    if (config.data) {
      if (!isEmptyObject(config.data)) {
        // formdata 不加签
        if (!(config.data instanceof FormData)) {
          signature = md5(JSON.stringify(config.data) + timestamp + md5(publicKey))
        }
      }
    } else if (config.params) {
      if (!isEmptyObject(config.params)) {
        signature = md5(dataSerialize(dataSort(config.params)) + timestamp + md5(publicKey))
      }
    }

    config.headers.signature = signature

    config.headers.timestamp = timestamp

    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (!res.success) {
      CnkiMessage.error(res.errMessage || '系统异常,请联系管理员')
      return Promise.reject(new Error(res.errMessage || '系统异常,请联系管理员', { cause: 'axios' }))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

export default service
